﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;

namespace AppCommon
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileManager
    {
        private string filePath = null;

        public async Task<uint> Download(string url, string filename)
        {
            var logger = await LogManager.GetInstrance();
            uint code = 0;
            if (filePath == null)
            {
                var root = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFolder path = await root.CreateFolderAsync("File", CreationCollisionOption.OpenIfExists);
                path = await path.CreateFolderAsync(DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day, CreationCollisionOption.OpenIfExists);
                var isExist = await FileIsExist(path, filename);
                if (!isExist)
                {

                    await logger.Debug("文件不存在，需要下载");
                    var _filename = await path.CreateFileAsync(filename);

                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation download = downloader.CreateDownload(new Uri(url), _filename);
                    await download.StartAsync();
                    ResponseInformation response = download.GetResponseInformation();
                    code = response.StatusCode;
                }
                else
                {
                    await logger.Debug("文件已存在，不需要下载");
                }
            }
            return code;
        }

        public async Task<bool> FileIsExist(StorageFolder path, string fileName)
        {
            IReadOnlyList<StorageFile> files = await path.GetFilesAsync();

            var query = files.Any(it => it.Name == fileName);

            return query;

        }
    }
}
